﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DisplayBoardInfo.Server.Model
{
    class Database
    {
        /// <summary>
        /// Creates new database.
        /// </summary>
        /// <exception cref="DatabaseException"></exception>
        public static void CreateDatabase()
        {
            DatabaseContextDataContext db = new DatabaseContextDataContext();
            try
            {
                db.CreateDatabase();

                InitializeDatabase(db);

                //
                //Save all changes
                db.SubmitChanges();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new DatabaseException(DatabaseException.Type.SQLException, ex.Message);
            }
            catch (Exception ex)
            {
                throw new DatabaseException(DatabaseException.Type.OtherException, ex.Message);
            }
        }

        public static void DeleteDatabase()
        {
            DatabaseContextDataContext db = new DatabaseContextDataContext();
            try
            {
                db.DeleteDatabase();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw new DatabaseException(DatabaseException.Type.SQLException, ex.Message);
            }
            catch (Exception ex)
            {
                throw new DatabaseException(DatabaseException.Type.OtherException, ex.Message);
            }
        }

        public static bool DatabaseExists()
        {
            DatabaseContextDataContext db = new DatabaseContextDataContext();
            return db.DatabaseExists();
        }

        /// <summary>
        /// Gets or sets host name or address.
        /// </summary>
        public static string Host
        {
            get 
            {
                string ds = GetParametrFromConnectionString("Data Source");
                return ds.Substring(0, ds.IndexOf(@"\"));
            }

            set 
            {
                SetParametrInConnectionString("Data Source", value + @"\" + Instance);
            }
        }

        /// <summary>
        /// Gets or sets name of database server instance.
        /// </summary>
        public static string Instance
        {
            get
            {
                string ds = GetParametrFromConnectionString("Data Source");
                return ds.Substring(ds.IndexOf(@"\") + 1);
            }

            set
            {
                SetParametrInConnectionString("Data Source", Host + @"\" + value.ToUpper());
            }
        }

        /// <summary>
        /// Gets or sets database name.
        /// </summary>
        public static string Name
        {
            get
            {
                return GetParametrFromConnectionString("Initial Catalog");
            }

            set
            {
                SetParametrInConnectionString("Initial Catalog", value);
            }
        }

        /// <summary>
        /// Username of database administrator.
        /// </summary>
        public static string Username
        {
            get
            {
                return GetParametrFromConnectionString("User ID");
            }

            set
            {
                SetParametrInConnectionString("User ID", value);
            }
        }

        /// <summary>
        /// Password for current user.
        /// </summary>
        public static string Password
        {
            get
            {
                return GetParametrFromConnectionString("Password");
            }

            set
            {
                SetParametrInConnectionString("Password", value);
            }
        }


        private static void InitializeDatabase(DatabaseContextDataContext db)
        {
            Role roleAdmin = new Role();
            roleAdmin.Name = "Administrator";
            roleAdmin.Description = "Administrator systemu z wszystkimi uprawnieniami.";
            db.Roles.InsertOnSubmit(roleAdmin);

            Role roleDoctor = new Role();
            roleDoctor.Name = "Lekarz";
            roleDoctor.Description = "Lekarz przyjmujący pacjentów. Zarządza kolejką.";
            db.Roles.InsertOnSubmit(roleDoctor);

            Role roleReceptionist = new Role();
            roleReceptionist.Name = "Recepcjonista";
            roleReceptionist.Description = "Recepcjonista zapisujący pacjentów";
            db.Roles.InsertOnSubmit(roleReceptionist);

            User defaultAdmin = new User();
            defaultAdmin.Username = "root";
            defaultAdmin.Password = "#1234qwer";
            defaultAdmin.Role1 = roleAdmin;
            db.Users.InsertOnSubmit(defaultAdmin);
        }

        private static string GetParametrFromConnectionString(string parametr)
        {
            Properties.Settings.Default.Reload();
            string connectionString = Properties.Settings.Default.ConnectionString;
            if (connectionString.Contains(parametr))
            {
                string cutedConnectionString = connectionString.Substring(connectionString.IndexOf(parametr + "=") + (parametr + "=").Length);
                return cutedConnectionString.Substring(0, cutedConnectionString.IndexOf(@";"));
            }
            else throw new IndexOutOfRangeException("Parametr is not exist");
        }

        private static void SetParametrInConnectionString(string parametr, string value)
        {
            string connectionString = Properties.Settings.Default.ConnectionString;
            if (connectionString.Contains(parametr))
            {
                string firstPart = connectionString.Substring(0, connectionString.IndexOf(parametr + "=") + (parametr + "=").Length);
                string cutedConnectionString = connectionString.Substring(connectionString.IndexOf(parametr + "=") + (parametr + "=").Length);
                string secondPart = cutedConnectionString.Substring(cutedConnectionString.IndexOf(@";"));
                Properties.Settings.Default.ConnectionString = firstPart + value + secondPart;
                Properties.Settings.Default.Save();
            }
            else
            {
                Properties.Settings.Default.ConnectionString = connectionString + ";" + parametr + "=" + value;
                Properties.Settings.Default.Save();
            }
        }
    }
}
